import { useMemberStore } from '@/stores'
import Request, { type HttpRequestConfig } from 'luch-request'

const service = new Request({
  baseURL: 'https://pcapi-xiaotuxian-front-devtest.itheima.net',
  timeout: 15 * 1000,
  custom: {
    loading: true
  }
})

// 服务器响应类型
export interface Data<T> {
  code: string
  msg: string
  result: T
}

// 万能请求
const myRequest = <T>(option: HttpRequestConfig) => {
  return service.request<T, Data<T>>(option)
}
// get
const myGet = <T>(url: string, params?: object, custom?: object) => {
  return myRequest<T>({
    url,
    method: 'GET',
    params,
    custom
  })
}
// post
const myPost = <T>(url: string, data?: object, custom?: object) => {
  return myRequest<T>({
    url,
    method: 'POST',
    data,
    custom
  })
}

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    // 加载框
    if (config.custom?.loading) {
      uni.showLoading({ title: '正在加载...', mask: true })
    }

    // 4. 添加 token 请求头标识
    const memberStore = useMemberStore()
    const token = memberStore.profile?.token
    if (token) {
      config.header = { ...config.header, Authorization: token }
    }

    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  (res) => {
    uni.hideLoading()

    return res.data
  },
  (error) => {
    uni.hideLoading()

    // 无 token 或者 token 错误，响应状态码是 401
    if (error.statusCode === 401) {
      const memberStore = useMemberStore()
      // 清除登录的信息
      memberStore.clearProfile()
      // 提示用户, 可能加载提示框还没有消失，所以延迟 10 毫秒
      setTimeout(() => {
        uni.showToast({
          title: '登录过期',
          icon: 'none'
        })
      }, 10)
      // 跳转到登录页
      uni.navigateTo({
        url: '/pages/login/login'
      })
    }

    return Promise.reject(error)
  }
)

export { myRequest, myGet, myPost }
